package service

import (
	"chat/log"
	"chat/models"
	"chat/utils"
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func CreateGroup(c *gin.Context) {
	var group models.Group
	if err := c.ShouldBindJSON(&group); err != nil {
		log.Error("参数错误")
		utils.RespFail(c.Writer, "参数错误")
		return
	}
	group.Type = 2
	group.Icon = "http://" + c.Request.Host + "/static/upload/avatar/default.jpeg"
	fmt.Printf("data%v\n", group)

	data, err := models.CreateGroup(&group)
	if err != nil {
		log.Error("数据库操作失败:", zap.Error(err))
		utils.RespFail(c.Writer, "创建群聊失败，请检查网络或联系管理员")
		return
	}
	var contact models.Contact
	contact.OwnerId = group.OwnerId
	contact.OwnerName = group.OwnerName
	contact.TargetId = data.ID
	contact.TargetName = data.Name
	contact.Type = 2
	if err := utils.Mysql.Table("contact_basic").Create(&contact).Error; err != nil {
		log.Error("数据库操作失败:", zap.Error(err))
	}

	for _, user := range group.Users {
		// 在这里处理每个用户，你可以根据需要执行一些操作
		var contact models.Contact
		info, _ := models.FindUserByID(user)
		contact.OwnerId = info.ID
		contact.OwnerName = info.Name
		contact.TargetId = data.ID
		contact.TargetName = data.Name
		contact.Type = 2
		fmt.Printf("%v\n", contact)
		if err := utils.Mysql.Table("contact_basic").Create(&contact).Error; err != nil {
			log.Error("数据库操作失败:", zap.Error(err))
		}
	}
	fmt.Printf("%v\n", data.ID)
	utils.RespOk(c.Writer, data, "群聊创建成功")
}

func GetGroupUsers(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	users, err := models.FindGroupUsers(uint(id))
	if err != nil {
		utils.RespFail(c.Writer, "发送未知错误，请联系管理员")
		return
	}
	utils.RespOkList(c.Writer, users, len(users))
}

func DissolveGroup(c *gin.Context) {
	group_id := c.Query("group_id")
	user_id := c.Query("user_id")
	owner := c.Query("group")
	if err := models.DissolveGroupUsers(group_id, user_id, owner); err != nil {
		utils.RespFail(c.Writer, "发送未知错误，请联系管理员")
		return
	}
	utils.RespOk(c.Writer, "data", "操作成功")
}

func InvitationUserToGroup(c *gin.Context) {
	var data models.Group
	if err := c.ShouldBindJSON(&data); err != nil {
		log.Error("参数错误")
		utils.RespFail(c.Writer, "参数错误")
		return
	}
	for _, user := range data.Users {
		// 在这里处理每个用户，你可以根据需要执行一些操作
		var contact models.Contact
		info, _ := models.FindUserByID(user)
		contact.OwnerId = info.ID
		contact.OwnerName = info.Name
		contact.TargetId = data.ID
		contact.TargetName = data.Name
		contact.Type = 2
		utils.Mysql.Table("contact_basic").Create(&contact)
	}
	utils.RespOk(c.Writer, nil, "邀请好友成功")
}

func MoveUserOnGroup(c *gin.Context) {
	var data models.Group
	if err := c.ShouldBindJSON(&data); err != nil {
		log.Error("参数错误")
		utils.RespFail(c.Writer, "参数错误")
		return
	}
	for _, user := range data.Users {
		utils.Mysql.Table("contact_basic").Where("owner_id = ? and target_id = ? and  type =2 ", user, data.ID).Delete(&models.GroupBasic{})
	}
	utils.RespOk(c.Writer, nil, "移除用户成功")
}
